package com.idol.dubbo.filter;

import com.idol.bean.TimerAttribute;
import com.idol.bean.TimerContainer;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.List;


/**
 * @author SupremeSir
 * @description Dubbo 过滤器
 * @className com.idol.dubbo.filter.TimerFilter
 * @date 2021/1/21 22:47
 **/
@Activate(group = {CommonConstants.CONSUMER})
public class TimerFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Result result = null;
        try {
            long startTime = System.currentTimeMillis();
            result = invoker.invoke(invocation);
            String methodName = invocation.getMethodName();
            TimerAttribute timerAttribute = TimerContainer.getContainer().get(methodName);
            if (null == timerAttribute) {
                timerAttribute = new TimerAttribute();
            }
            // 这里需要做同步，否则两个数组内容个数会不一样
            synchronized (String.class) {
                List<Long> timeList = timerAttribute.getTimeList();
                timeList.add(startTime);
                List<Integer> castTimeList = timerAttribute.getCastTimeList();
                castTimeList.add((int) (System.currentTimeMillis() - startTime));
                TimerContainer.getContainer().put(methodName, timerAttribute);
            }
        } catch (RpcException e) {
            e.printStackTrace();
        }
        return result;
    }
}
